<template>
<div>
  <el-card class="box-card">
    <el-page-header @back="goBack" :content="modular_id === 0 ? '新增模块' : '编辑模块'"></el-page-header>
  </el-card>
  <div>
    <el-card class="ivu-mt">
      <el-form :model="addForm" :rules="addRules" ref="AddRefForm" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="title">
              <el-input v-model="addForm.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input v-model="addForm.icon"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input v-model="addForm.keyword"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述">
              <el-input v-model="addForm.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路由" prop="path">
              <el-input v-model="addForm.path"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="addForm.status">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="addForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-upload
          style="display: none"
          class="quill-avatar-uploader"
          :action="upload.url"
          :headers="upload.headers"
          :accept="upload.accept"
          :data="upload.data"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"></el-upload>
        <el-form-item label="内容">
          <el-row v-loading="quillUpdateImg">
            <quill-editor ref="myQuillEditor" v-model="addForm.content"  class="ql-editor-class" :options="editorOption"></quill-editor>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveModular">{{modular_id === 0 ? '立即创建' : '立即更新'}}</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</div>
</template>

<script>
const toolbarOptions = [
  // toggled buttons
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote'],
  // custom button values
  [{'header': 1}, {'header': 2}],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  // superscript/subscript
  [{'script': 'sub'}, {'script': 'super'}],
  // outdent/indent
  [{'indent': '-1'}, {'indent': '+1'}],
  // text direction
  [{'direction': 'rtl'}],
  [{'size': ['10px', '12px', '14px', '16px', '18px', '20px', '22px', '24px', '26px', '32px', '48px']}],
  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  // dropdown with defaults from theme
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['image'],
  // remove formatting button
  ['clean']
]
export default {
  name: "add",
  data(){
    return{
      modular_id:0,
      quillUpdateImg:false,
      addForm:{
        title:'',
        icon:'',
        keyword:'',
        description:'',
        path:'',
        status:true,
        remark:'',
        content:'',
      },
      upload: {
        url: this.$action_url,
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data:{
          folder:'modular_img'
        },
        name: 'file',
        accept: 'image/*',
        limitCount: 1,
      },
      addRules:{
        title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 28, message: '长度在 2 到 28 个字符', trigger: 'blur' }
        ]
      },
      //编辑器配置
      editorOption:{
        placeholder: '请输入内容',
        theme: 'snow',
        modules: {
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container:toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector(".quill-avatar-uploader input").click();
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  created() {
    this.modular_id = sessionStorage.getItem('modular_id') === null ? 0 : sessionStorage.getItem('modular_id')
    if (this.modular_id > 0){
      this.editModular(this.modular_id);
    }
  },
  methods:{
    goBack(){
      this.$router.go(-1);//返回上一层
    },
    // 上传图片前
    beforeUpload(res, file) {
      // 打开上传动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccess(res,file,fileList) {
      let quill = this.$refs.myQuillEditor.quill
      if (res.code !== 200) return this.$message.error('上传失败');
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片  res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', this.$http_url + 'storage/' + res.data.list.path)
      // 调整光标到最后
      quill.setSelection(length + 1)

      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadError(res, file) {
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    async editModular(modular_id){
      const {data: res} = await this.$http.get('dashboard/modular_show/' + modular_id)
      if (res.code !== 200) return this.$message.error('获取新闻失败');
      this.addForm = res.data.list;
    },
    saveModular(){
      if (this.modular_id > 0){
        this.$set(this.addForm, 'id', this.modular_id)
      }
      this.$refs.AddRefForm.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        const {data: result} = await this.$http.post('dashboard/modular_save', this.addForm)
        console.log(result)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('新增成功')

        this.$router.push('/dashboard/modular_list')
      })
    }
  }
}
</script>

<style scoped>

</style>
